#* -coding: utf - 8 -* -
"""
 Copyright 2010 Kruglov M.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
"""

import inspect
import subprocess
import sys
import time

def whoIsMydaddy():
#    return str(inspect.stack()[2][0].__class__.__name__)
    return str(inspect.stack())

def getTimeNow():

    res = dict()
    tm = time.localtime()
    struct_attrs = ['tm_year','tm_mon','tm_mday','tm_hour','tm_min','tm_sec','tm_wday','tm_yday','tm_isdst']

    for attr in struct_attrs:
        name = attr
        value = str(tm.__getattribute__(attr))
        if len(value) == 1: value = "0" + value
        res[name[3:]] = value
    return res

class Sandbox(object):
        def __getattr__(self,name):
            try:
                return object.__getattribute__(self,'child__' + name)
            except AttributeError:
                return object.__getattribute__(self,name)

        def getFuncs(self):
            res = []
            for each in dir(self):
                if each.startswith('child__'):
                    res.append(self.__getattribute__(each))
            return res

        def __iter__(self):
            return iter(self.getFuncs())

class setIntervalDecorator(object):

    def __init__(self,delay):
        self.delay = delay

    def __call__(self,fn):
        def new(*args):
            while True:
                time.sleep(self.delay)
                fn(*args)
        return new

def mergeArrays(lists):
    res = []
    for i in lists:
        for j in i:
            res.append(i)
    return res

def frange(start,end=None,inc=None):
    """A range function, that does accept float increments"""

    if end == None:
        end = start + 0.0
        start = 0.0

    if inc == None:
        inc = 1.0

    L = []
    while 1:
        next = start + len(L) * inc
        if inc > 0 and next >= end:
            break
        elif inc < 0 and next <= end:
            break
        L.append(next)

    return L

def getClassesAsList(module):
#    __import__(mod, globals(), locals())
    __import__(module)
    res = list()
    for name,obj in inspect.getmembers(sys.modules[module]):
        if inspect.isclass(obj):
            res.append(name)
    return res

def arrayUniq(arr):
    els = []
    for each in arr:
        if each not in els:
            els.append(each)

    return els

def keySortDict(mydict):
    res = dict()
    keylist = mydict.keys()
    keylist.sort()
    for key in keylist:
        res[key] = mydict[key]
    return res


def arrayToString(a,quotes=False,delimeter=','):
    res = ""
    for i in a:
        if quotes:
            res += "'" + str(i).strip() + "'" + str(delimeter)
        else:
            res += str(i).strip() + str(delimeter)
    return res[0:-len(delimeter)]

def execute(comm,pipe=True):
    comm = comm.split()
    if pipe:
        return subprocess.Popen(comm,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0].strip()
    else:
        return subprocess.Popen(comm,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

